import { reqLogin, reqGetUserInfo, reqGetUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

// 这里名字字段是固定的，一定要和上下保持一致 而且不要自由发挥加个s去个s
const state = {
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  // 设置token
  setToken(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  // 设置用户信息
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  },
  // 删除token
  removeToken(state) {
    // 删除vuex
    state.token = ''
    // 删除本地的
    removeToken()
  },
  // 删除用户信息
  removeUserInfo(state) {
    // 删除vuex
    state.userInfo = {}
  }
}
const actions = {
  async login(context, data) {
    // const { data: { data: token }} = await reqLogin(data)
    // console.log(token)
    const res = await reqLogin(data)
    const token = res.data
    console.log(token)
    context.commit('setToken', token)
  },
  // 获取用户资料
  async getUserInfo({ commit }) {
    const { data: data1 } = await reqGetUserInfo()
    // console.log(data)
    const { data: data2 } = await reqGetUserDetailById(data1.userId)
    console.log(data2)
    const res = { ...data1, ...data2 }
    commit('setUserInfo', res)
    return res
  },
  logout({ commit }) {
    // 删除token
    commit('removeToken')
    // 删除用户信息
    commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
